#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const size_t gnum = 1024;

enum
{
    SOCKET_ERR = 1,
    Usage_ERR
};

class udpClient
{
public:
    udpClient(std::string serverip, uint16_t serverport)
        : _sockfd(-1), _serverip(serverip), _serverport(serverport), _quit(false)
    {
    }
    void initClient()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            std::cerr << "socket error: " << errno << ":" << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        std::cout << "socket success, sockfd: " << _sockfd << std::endl;
    }

    static void *readmessage(void *args)
    {
        int sockfd = *(static_cast<int*>(args));
        pthread_detach(pthread_self());
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);

        char buffer[gnum];
        while(true)
        {
            int s = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&tmp, &len);
            if (s >= 0)
            {
                buffer[s] = 0;
                std::cout << buffer << std::endl;
            }
        }

    }
    void run()
    {
        //用多线程分离读消息和发消息
        pthread_create(&_readtid, nullptr, readmessage, (void*)&_sockfd);
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        server.sin_port = htons(_serverport);

        std::string message;
        char line[gnum];
        while (!_quit)
        {
            // std::cout << "请输入你要发送的消息#";
            fprintf(stderr,"Enter #");
            fflush(stderr);
            // std::cin >> message;
            fgets(line, sizeof(line), stdin);

            message = line;
            //把\n去了
            if(message.size()>0)message[message.size()-1] = 0;
            // 操作系统通过这个接口，自动bind你的IP和port
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        }
    }
    ~udpClient()
    {
    }

private:
    int _sockfd;
    std::string _serverip;
    uint16_t _serverport;
    bool _quit;
    pthread_t _readtid;
};